<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2021/3/31
 * Time: 1:00
 */

namespace app\adminapi\validate;

use think\Session;

class Admin extends Common
{
    protected $rule = [
        'username' => 'require|max:20|usernameExists',
        'password' => 'require|max:20|passwordCorrect',
        'code' => 'require|max:4|codeCorrect',
    ];

    protected $message = [
        'username.require' => '用户名必须',
        'username.max' => '用户名长度错误',
        'username.usernameExists' => '用户名不存在',
        'password.require' => '密码必须',
        'password.max' => '密码长度错误',
        'password.passwordCorrect' => '密码错误',
        'code.require' => '验证码必须',
        'code.max' => '验证码长度错误',
        'code.codeCorrect' => '验证码错误',
    ];

    protected $scene = [
        'login' => ['username', 'password', 'code'],
    ];

    /**
     * 用户名存在
     * @param $value
     * @param $rule
     * @param $data
     * @return bool|string
     */
    protected function usernameExists($value, $rule, $data)
    {
        if (model('\app\adminapi\model\Admin')->where("username='{$value}'")->count()) {
            return true;
        }
        return false;
    }

    /**
     * 密码校验
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     */
    protected function passwordCorrect($value, $rule, $data)
    {
        $admin = model('\app\adminapi\model\Admin')
            ->where("username='{$data["username"]}'")
            ->field('salt, password')
            ->find();
        if(empty($admin)) return false;

        if(\app\adminapi\model\Admin::getEncryptPassword($value, $admin->salt)!=$admin->password)
        {
            return false;
        }
        return true;
    }

    protected function codeCorrect($value, $rule, $data)
    {
        if(!check_verify($value))
        {
            return false;
        }
        return true;
    }

}